
<script>
import { getMenu } from '@/menu/index';

export default {
  components: {
  },
  props: {
    type: String,
  },
  data () {
    return {
      allMenuPath: [],
    };
  },
  computed: {
    menuList () {
      const list = getMenu(this.type);
      this.$nextTick(this.initMenu);
      return list;
    },
    defaultOpened () {
      return this.menuList.map(this.getMenuUrl);
    },
    defaultActive () {
      const path = this.$route.path;
      if (this.allMenuPath.includes(path)) {
        return path;
      }
      let maxIndex = 0;
      let currentPath = path;
      for (const val of this.allMenuPath) {
        if (path.includes(val) && val.length > maxIndex) {
          maxIndex = val.length;
          currentPath = val;
        }
      }
      return currentPath;
    },
  },

  methods: {
    initMenu () {
      const forEachAppend = (list) => {
        list.forEach(menu => {
          if (Array.isArray(menu.children)) {
            forEachAppend(menu.children);
          } else {
            this.allMenuPath.push(this.getMenuUrl(menu));
          }
        });
      };
      this.allMenuPath = [];
      forEachAppend(this.menuList);
    },
    getMenuUrl (menu) {
      return `/${this.type}${menu.url}`;
    },

    onClickMenu (menu) {
      const url = this.getMenuUrl(menu);
      if (menu.url.indexOf('http') === 0) {
        window.open(url);
      } else if (url !== this.$route.fullPath) {
        this.$router.push(url);
      }
    },

    renderMenuList (list) {
      return list.map(menu => this.renderMenuItem(menu));
    },

    renderMenuItem (menu) {
      const url = this.getMenuUrl(menu);

      const children = (
        <span slot="title">
          {menu.icon && <i class={menu.icon}></i>}
          <span>{menu.title}</span>
        </span>
      );

      if (!menu.children || menu.children.length === 0) {
        return (
          <el-menu-item
            key={url}
            index={url}
            route={url}
            onClick={() => this.onClickMenu(menu)}
          >
            {children}
          </el-menu-item>
        );
      } else {
        return (
          <el-submenu
            key={url}
            index={url}
          >
            {children}
            {this.renderMenuList(menu.children)}
          </el-submenu>
        );
      }
    },
  },
  render (h) {
    return (
      <el-menu
        default-active={this.defaultActive}
        default-openeds={this.defaultOpened}
      >
        {this.renderMenuList(this.menuList)}
      </el-menu>
    );
  },
};
</script>

<style lang="scss" scoped>
.el-menu {
  height: 100%;
  border: none;
}
</style>
